<template>
    <div class="m-view-formula">
        <div class="m-formulaInput">
            <input type="file" multiple="false" id="sheetjs-input" accept="xls,xlsx" @change="onchange" />
            <!--<button type="button" id="downLoadDemo" @click="downLoadDemo">下载模板</button>-->
            <!--<a href="下载模板.xls" download target="_blank">下载模板</a>-->
        </div>
        <ag-grid-vue class="m-agTableContent ag-theme-balham" :gridOptions="gridOptions" :columnDefs="columnDefs" :rowData="rowData"></ag-grid-vue>

    </div>
</template>

<style lang="less">
.m-view-formula {
    .m-formulaInput{
        margin-bottom: 10px;
    }
    .m-agTableContent{
        height: 350px;
        margin-bottom: 5px;
    }
}
</style>

<script>
import XLSX from "xlsx";
import _Api from "@/api";
import localeText from "@/i18n/agGridText";

export default {
    data() {
        return {
            gridOptions: null,
            columnDefs: [],
            rowData: [],
            cols: []
        };
    },
    components: {},
    methods: {
        onchange: function(evt) {
            var files = evt.target.files;
            if (!files || files.length == 0) return;

            var self = this;
            var excelFile = files[0];

            var reader = new FileReader();
            reader.onload = function(e) {
                // 数据预处理
                var binary = "";
                var bytes = new Uint8Array(e.target.result);
                var length = bytes.byteLength;
                for (var i = 0; i < length; i++) {
                    binary += String.fromCharCode(bytes[i]);
                }

                /* 读取 workbook */
                var wb = XLSX.read(binary, {
                    type: "binary"
                });

                /* 选择第一个sheet */
                var wsname = wb.SheetNames[0];
                var ws = wb.Sheets[wsname];

                /* excel转换json数组,加上{header:1}是普通数组，不写是对象数组 */
                var json = XLSX.utils.sheet_to_json(ws);

                self.cols = [];
                self.columnDefs = [];
                //              for(var key in json[0]){
                //              	
                //                  var h = {};
                //                  h.headerName = key;
                //                  h.field = key;
                //                  h.width = 100;
                //                  self.columnDefs.push(h);
                //
                //                  if(key.indexOf('-') > -1){
                //                      self.cols.push(key.split('-')[1]);
                //                  }
                //              }

                //				筛选数据
                //				for(var i = 0;i< json.length;i++)
                //				{
                //					for(var j = i+1;j<json.length;j++)
                //					{
                //						if(json[i]["物料编号-matCode"].trim() == json[j]["物料编号-matCode"].trim() && json[i]["工序-proName"].trim() == json[j]["工序-proName"].trim())
                //							json.splice(j,1)
                //					}
                //				}
                var that = this;
                _Api.queryRalInspetionISCode(json).then(function(response) {
                    
                    var data = response.data;
                    if (data.code == "1") {
                        for (var key in data.rows[0]) {
                            var h = {};
                            h.headerName = key;
                            h.field = key;
                            h.width = 100;
                            self.columnDefs.push(h);

                            if (key.indexOf("-") > -1) {
                                self.cols.push(key.split("-")[1]);
                            }
                        }
                        self.rowData = data.rows;
                    } else {
//                      alert("获取失败！");
						that.$message.error("获取失败");
                    }
                });
                //self.rowData = json;
            };

            reader.readAsArrayBuffer(excelFile);
        },
        importToRdb(tbName, primaryKey) {
            var excelData = {};
            excelData.creator = this.$global.user.loginName;
            excelData.createId = this.$global.user.username;
            excelData.primaryKey = primaryKey;
            excelData.tableName = tbName;
            excelData.cols = this.cols;

            if (this.rowData.length > 0) {
                var rd = [];
                for (var i = 0; i < this.rowData.length; i++) {
                    //重新设置keyName
                    var row = {};
                    for (var key in this.rowData[0]) {
                        if (key.indexOf("-") > -1) {
                            var newKey = key.split("-")[1];
                            var value = this.rowData[i][key];
                            if (!value) value = "";
                            row[newKey] = value;
                        }
                    }
                    rd.push(row);
                }
                excelData.rows = rd;
                console.log(JSON.stringify(excelData));
                _Api.inputExcel(excelData).then(function(response) {
                    //调用接口
                    var data = response.data;
                    console.log(data);
                    if (data.code == "0") {
                        that.$alert(data.info, {
                            confirmButtonText: "确定"
                        });
                    } else {
                        that.$alert("导入成功！", {
                            confirmButtonText: "确定"
                        });
                        that.rowData = [];
                    }
                });
            } else {
                that.$alert("无可导入数据！", {
                    confirmButtonText: "确定"
                });
            }
        }
    },
    beforeMount() {
        console.log(this.$global.user);
        this.gridOptions = {
            context: {
                componentParent: this
            },
            localeText: localeText,
           	enableColResize:true
        };
    },
    mounted() {
        this.gridOptions.api.sizeColumnsToFit();
    }
};
</script>